package com.rop.znyx.acl.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.acl.mapper.PermissionMapper;
import com.rop.znyx.acl.mapper.RolePermissionMapper;
import com.rop.znyx.common.util.PermissionHelper;
import com.rop.znyx.model.acl.Permission;
import com.rop.znyx.model.acl.RolePermission;
import com.rop.znyx.acl.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/6/16
 * Time: 13:36
 * Description: 菜单管理
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final RolePermissionMapper rolePermissionMapper;

    /**
     * 查询所有菜单
     */
    @Override
    public List<Permission> queryAllMenu() {
        //获取全部权限数据
        List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

        //把权限数据构建成树形结构数据
        return PermissionHelper.build(allPermissionList);
    }

    /**
     * 递归删除
     */
    @Override
    public boolean removeChildById(Long id) {
        List<Long> idList = new ArrayList<>();
        this.selectChildListById(id, idList);
        idList.add(id);
        baseMapper.deleteBatchIds(idList);
        return true;
    }

    /**
     * 获取角色拥有的所有权限
     * @param id 角色id
     */
    @Override
    public List<Permission> findRoleByUserId(Long id) {

        // 查询所有菜单
        List<Permission> permissionList = baseMapper.selectList(null);

        // 获取角色权限所有数据
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().eq("role_id", id).select("permission_id"));
        List<Long> existPermissionId = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());

        // 对菜单进行分类
        List<Permission> assignPermission = new ArrayList<>();
        permissionList.forEach(r->{
            r.setSelect(existPermissionId.contains(r.getId()) ? Boolean.TRUE : Boolean.FALSE);
        });

        // 返回结果
        return PermissionHelper.build(permissionList);
    }

    /**
     * 给角色分配菜单
     */
    @Override
    @Transactional
    public boolean doAssign(Long roleId, Long[] permissionId) {
        // 根据角色id删除旧角色
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRoleId, roleId);
        rolePermissionMapper.delete(wrapper);

        // 再新增选中的角色
        int rows = 0;
        if (ArrayUtil.isNotEmpty(permissionId)) {
            rows = rolePermissionMapper.batchInsert(roleId, permissionId);
        }
        return rows < 0 ? Boolean.FALSE : Boolean.TRUE;
    }

    /**
     * 递归获取子节点
     */
    private void selectChildListById(Long id, List<Long> idList) {
        List<Permission> childList = baseMapper.selectList(new QueryWrapper<Permission>().eq("pid", id).select("id"));
        childList.forEach(item -> {
            idList.add(item.getId());
            this.selectChildListById(item.getId(), idList);
        });
    }
}
